﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using SecureConnection;

namespace RemoteCode
{
    public class NexumListener
    {
        private Connection listener;

        public ushort Port { get; protected set; }
        public byte[] Key { get; protected set; }

        public bool UseCache { get; private set; }

        public NexumListener(ushort port, bool useCache, byte[] key = null)
        {
            this.Port = port;
            this.Key = key;
            this.UseCache = useCache;
        }

        public void Listen()
        {
            listener = new Connection(Key == null , Key);

            listener.Listen(Port, 100);

            listener.BeginAccept(AcceptCallback);
        }
        public void Stop()
        {
            listener.Close();
        }

        private void AcceptCallback(Connection accepted, bool err, Exception ex, Connection sender)
        {
            if (err)
            {
                while (OnError == null)
                    Thread.Sleep(100);

                OnError(ex);
            }

            Nexum n = new Nexum(UseCache, Key, accepted);

            while (OnAccept == null)
                Thread.Sleep(100);
            OnAccept(n, this);

            listener.BeginAccept(AcceptCallback);
        }

        public delegate void OnAcceptHandler(Nexum n, NexumListener sender);
        public event OnAcceptHandler OnAccept = null;

        public delegate void OnErrorHandler(Exception ex);
        public event OnErrorHandler OnError = null;
    }
}
